package com.blog.webSocket.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blog.Utils.Result;
import com.blog.bean.domain.User;
import com.blog.bean.dto.MessageDTO;
import com.blog.exception.ServiceException;
import com.blog.mapper.UserMapper;
import com.blog.bean.vo.MessageDetailVO;
import com.blog.bean.vo.MessageListVO;
import com.blog.bean.vo.MessageVO;
import com.blog.webSocket.domain.ChatList;
import com.blog.webSocket.domain.ChatMessage;
import com.blog.webSocket.mapper.ChatListMapper;
import com.blog.webSocket.mapper.ChatMessageMapper;
import com.blog.webSocket.service.ChatService;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 任浩
 * @version 1.0
 */

@Slf4j
@Service(value = "chatService")
public class ChatServiceImpl implements ChatService {

    @Autowired
    private ChatListMapper chatListMapper;

    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @Autowired
    private UserMapper userMapper;


    @Override
    public String selectAssociation(String fromUser, String toUser) {
        return null;
    }

    @Override
    public void isFirstChat(String fromUser, String toUser,Boolean isExists) {
        //todo 到数据库查当前两个用户是否第一次聊天。
        QueryWrapper<ChatList> queryWrapper = new QueryWrapper<ChatList>()
                                    .eq("from_user", fromUser)
                                    .eq("to_user",toUser)
                                    .eq("status",0);

        ChatList chatList = chatListMapper.selectOne(queryWrapper);

        if(chatList == null){
            log.info("{} 和 {} 第一次聊天",fromUser,toUser);
            //初始化聊天列表。

            //消息是否已读，可以根据对方是否已上线来判断。
            chatList = ChatList.builder().fromUser(fromUser)
                    .toUser(toUser).unread(0).build();
            int insert = chatListMapper.insert(chatList);
            if(insert != 1){
                log.info("插入聊天列表数据失败");
                throw new ServiceException("插入聊天列表数据失败");
            }

            chatList = ChatList.builder().fromUser(toUser)
                    .toUser(fromUser).unread(0).build();
            insert = chatListMapper.insert(chatList);
            if(insert != 1){
                log.info("插入聊天列表数据失败");
                throw new ServiceException("插入聊天列表数据失败");
            }
        }
        else {
            log.info("当前聊天记录已存在");
        }
    }

    @Override
    public void saveMessage(ChatMessage chatMessage) {
        //将消息存入数据库
        int insert = chatMessageMapper.insert(chatMessage);
        if(insert != 1){
            log.info("将消息存入数据库失败");
            throw new ServiceException("将消息存入数据库失败");
        }
    }

    /**
     * 获取当前用户聊天列表
     * @param fromUser
     * @return
     */
    @Override
    public Result<MessageListVO> getFromUserChatList(String fromUser, MessageDTO messageDTO) {
        MessageListVO messageListVO = new MessageListVO();

        log.info("fromUser: {}",fromUser);
        Page<ChatList> page = new Page<>(messageDTO.getPage(),messageDTO.getPageNum());
        Page<ChatList> data = chatListMapper.selectPage(page,new QueryWrapper<ChatList>()
                                                                    .eq("from_user", fromUser)
                                                                    .eq("status",0)
                                                                    .orderByDesc("create_time"));
        List<ChatList> records = data.getRecords();
        log.info("当前查询处理的列表数据为：{}",records);

        int unread = 0;
        List<MessageVO> list = new ArrayList<>();
        for (ChatList chatList : records) {
            //计算所有的未读消息
            unread += chatList.getUnread().intValue();

            //同时取出最近的一条消息。
            ChatMessage chatMessage = chatMessageMapper.selectRecentMessage(fromUser,chatList.getToUser());

            //计算出当前聊天的数量
            Integer count = chatMessageMapper.selectNumber(fromUser,chatList.getToUser());

            //查找出发送聊天的用户信息
            User user = userMapper.selectById(Integer.parseInt(chatList.getToUser()));

            MessageVO messageVO = MessageVO.builder().id(chatMessage.getId())
                    .fromId(Integer.parseInt(chatList.getFromUser()))
                    .toId(Integer.parseInt(chatList.getToUser()))
                    .content(chatMessage.getContent())
                    .createTime(chatMessage.getSendTime())
                    .count(count)
                    .unreadMessageCount(chatList.getUnread())
                    .username(user.getUsername())
                    .headerUrl(user.getHeaderUrl()).build();
            list.add(messageVO);
        }

        Long total = chatListMapper.selectCount(null);
        log.info("查询出来的总数为：" + total +"  " + data.getSize());
        messageListVO.setData(list);
        messageListVO.setCurPage(messageDTO.getPage());
        messageListVO.setUnreadMessageTotal(unread);
        messageListVO.setTotal(total);
        return Result.success(messageListVO);
    }

    /**
     * 查找用户的聊天记录
     * @param fromUser
     * @param messageDTO
     * @return
     */
    @Override
    public Result<MessageDetailVO> getRecentChatRecords(String fromUser, MessageDTO messageDTO) {
        MessageDetailVO messageDetailVO = new MessageDetailVO();

        User toUser = userMapper.selectById(messageDTO.getToId());
        User user = userMapper.selectById(Integer.parseInt(fromUser));

        //开启分页
        PageHelper.startPage(messageDTO.getPage(),messageDTO.getPageNum());
        //将消息按照发送时间升序排序。
        com.github.pagehelper.Page<ChatMessage> page = chatMessageMapper.selectMessageList(fromUser,messageDTO.getToId().toString(),1);

        messageDetailVO.setTotal(page.getTotal()); //设置总数据
        messageDetailVO.setCurPage(messageDTO.getPage());
        List<ChatMessage> data= page.getResult();
        log.info("从数据库查询出来的值为：{}",page.getResult());

        List<MessageVO> result = new ArrayList<>();
        data.forEach(v ->{
            String headerUrl = null;
            Integer isCurrent = null;
            if(fromUser.equals(v.getFromUser())){
                headerUrl = user.getHeaderUrl();
                isCurrent = 1;
            }
            else {
                headerUrl = toUser.getHeaderUrl();
                isCurrent = -1;
            }

            MessageVO messageVO = MessageVO.builder()
                                    .content(v.getContent())
                                    .createTime(v.getSendTime())
                                    .id(v.getId())
                                    .headerUrl(headerUrl)
                                    .isCurentMsg(isCurrent)
                                    .build();
            result.add(messageVO);
        });
        log.info("result: {}",result);
        messageDetailVO.setData(result);


        messageDetailVO.setOneselfUser(user);
        messageDetailVO.setOtherUser(toUser);

        //修改信息的状态为已读
        chatListMapper.update(ChatList.builder().unread(0).build(),new QueryWrapper<ChatList>()
                                                            .eq("from_user",fromUser)
                                                            .eq("to_user",messageDTO.getToId()));
        log.info("处理完的结果数据为：{}",messageDetailVO);
        return Result.success(messageDetailVO);
    }

    @Override
    public void updateWindows(String fromUser, String toUser) {

    }

    @Override
    public Result getUnreadTotalNumber(String username) {
        return null;
    }

    @Override
    public void resetWindows(String username) {

    }
}
